package com.sun.showcase.controller.app.mall;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.sun.showcase.biz.mall.service.ShoppingCartService;
import com.sun.showcase.client.query.mall.ShoppingCartQuery;
import com.sun.showcase.pojo.DataGrid;
import com.sun.showcase.pojo.Result;
import com.sun.showcase.utils.ExecuteResult;
import com.sun.showcase.utils.StringConstant;
@CrossOrigin
@Controller("appShoppingCartController")
@RequestMapping(value="/app/cart") 
public class ShoppingCartController{
	
	@Autowired
	private ShoppingCartService shoppingCartService;
	
	private Result result = new Result();

	/**
	 * 获得分页数据表格
	 */
	@ResponseBody
	@RequestMapping(value = "/datagrid")
	public Result datagrid(ShoppingCartQuery shoppingCartQuery) {
		if(StringUtils.isEmpty(shoppingCartQuery.getUserId())) {
			result.setSuccess(false);
			result.setMsg("无效用户！");
			return result;
		}
		DataGrid dg = shoppingCartService.datagrid(shoppingCartQuery);
		result.setSuccess(true);
		result.setData(dg);
		return result;
	}
	

	/**
	 * 添加一个ShoppingCart
	 */
	@ResponseBody
	@RequestMapping(value="add")
	public Result add(ShoppingCartQuery shoppingCartQuery) {
		ExecuteResult<String> res = shoppingCartService.save(shoppingCartQuery);
		result.setSuccess(res.isSuccess());
		if(res.isSuccess()) {
			result.setMsg(res.getSuccessMessage());
		}else {
			result.setMsg(res.getErrorMessages().get(0));
		}
		return result;
	}


	/**
	 * 更新数量
	 */
	@ResponseBody
	@RequestMapping(value="update")
	public Result update(ShoppingCartQuery shoppingCartQuery) {
		ExecuteResult<String> res = shoppingCartService.updateBuyNum(shoppingCartQuery);
		result.setSuccess(res.isSuccess());
		if(res.isSuccess()) {
			result.setMsg(res.getSuccessMessage());
		}else {
			result.setMsg(res.getErrorMessages().get(0));
		}
		return result;
	}
	/**
	 * 更新数量
	 */
	@ResponseBody
	@RequestMapping(value="delete")
	public Result delete(String ids) {
		if(ids.indexOf(StringConstant.COMMA)>=0) {
			shoppingCartService.delete(ids.split(StringConstant.COMMA));
		}else {
			String[] idAry = {ids};
			shoppingCartService.delete(idAry);
		}
		result.setSuccess(true);
		result.setMsg("删除成功！");
		return result;
	}
	@ResponseBody
	@RequestMapping(value="clear")
	public Result clear(String userId) {
		shoppingCartService.deleteByUserId(userId);
		result.setSuccess(true);
		result.setMsg("删除成功！");
		return result;
	}
}
